import 'dart:math';

import 'package:base_flutter/base_flutter.dart';
// import 'package:esc_pos_bluetooth/esc_pos_bluetooth.dart';
// import 'package:esc_pos_utils/esc_pos_utils.dart';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:ls_work/util/esc_print_data.dart';
import 'package:ls_work/util/ext_utils.dart';

import '../../message/message_config.dart';
import '../../net/post_request.dart';
import '../../net/response/food/regular_week_menu_list_data.dart';
import '../../net/response/food/scan_old_data.dart';
import '../../net/response/food/week_menu_list_data.dart';
import '../../print/sunmi_print_utils.dart';
import '../../print/week_print_data.dart';
import '../../widgets/bottom_input_widget.dart';

class RegularWeekMenuViewModel
    extends BaseListViewModel<RegularWeekMenuContent> {
  final String? siteId;
  final String? time;
  final String? orderModelType;
  final ScanOldData? oldData;
  final String? useType;

  var hasLimitMoney = false;

  RegularWeekMenuViewModel(BuildContext context,
      {this.siteId, this.time, this.orderModelType, this.oldData, this.useType})
      : super(context) {
    hasLimitMoney = oldData?.limitData != null;
  }

  RegularWeekMenuListData? menuData;

  double menuWidth = 100;

  var dateList = <String>[];

  // PrinterBluetoothManager printerManager = PrinterBluetoothManager();

  ///提取日期
  void requestDateList() {
    listItems.forEach((element) {
      element.goodsInfo?.forEach((type) {
        var dateStr = getDate(type.weekDay??0);
        if (!dateList.contains(dateStr)) {
          dateList.add(dateStr);
        }
      });
    });
    menuWidth = dateList.length * 180.0 + 110;
    print(menuWidth);
  }

  @override
  Future<List<RegularWeekMenuContent>> requestListData() async {
    var data = await PostRequest.weekMenu(
        time, siteId, oldData?.selectOldId.toString(), orderModelType);
    if ('0' == data['code'].toString()) {
      if (data['data'] != null) {
        menuData = RegularWeekMenuListData.fromJson(data['data']);
        menuData?.menuJson?.content?.forEach((time) {
          time.goodsInfo?.forEach((date) {
            var foodLength = date.goodsList?.length ?? 0;
            date.maxnumber = time.selectNumber;
            // date.foodLength = max(foodLength, date.foodLength);
            date.timeTypeId = time.timeSection.toString();
            time.foodLength = max(foodLength, time.foodLength??0);
            date.weekDate = getDateValue(date.weekDay??0);
            date.goodsList?.forEach((food) {
              if (food.status == 1) {
                date.selectItems.add(food);
              }
              food.foodDate = getDate(date.weekDay??0);
              food.foodEndTime = time.rangeEnd ?? "";
              food.oldStatus = food.status;
              food.oldNumber = food.number??0;
              // food.canSelect = canSelect(food);
            });
          });
          // time.foodLength += time.foodLength;
        });
        return menuData?.menuJson?.content??[];
      } else {
        throw '未获取到周菜单';
      }
    } else {
      throw data['msg'];
    }
  }

  String getDate(int weekDay) {

    return getDateValue(weekDay)?.toDateStr([yyyy, '-', mm, '-', dd])??"";
  }

  DateTime? getDateValue(int weekDay) {
    DateTime? monday;
    if (time == '1') {
      var now = DateTime.now();
      monday = now.add(Duration(days: -1 * now.weekday + 1));
    }

    if (time == '2') {
      var now = DateTime.now();
      monday = now.add(Duration(days: 7 - now.weekday + 1));
    }

    if (time == '3') {
      var now = DateTime.now();
      monday = now.add(Duration(days: 7 - now.weekday + 7 + 1));
    }

    var date = monday?.add(Duration(days: weekDay - 1));

    return date;
  }

  bool canSelect(GoodsList food) {
    // if(food.flag??false){
    if (food.foodEndTime.isNullOrEmpty()) {
      if(1==food.isTake){
        return false;
      }else{
        return true;
      }
    } else {
      var now = DateTime.now();
      var today = now.toDateStr([yyyy, '-', mm, '-', dd]);
      var foodDate = DateTime.parse('${food.foodDate} 00:00:00');
      var nowTime = DateTime.parse('${today} 00:00:00');
      if (foodDate.isBefore(nowTime)) {
        print(food.foodDate);
        return false;
      }
      if (food.foodDate == today) {
        var endTime = DateTime.parse('${today} ${food.foodEndTime}');
        // print("endTime===>${today} ${food.foodEndTime}");
        if (now.isAfter(endTime)) {
          return false;
        } else {
          if(1==food.isTake){
            return false;
          }else{
            return true;
          }
        }
      } else {
        if(1==food.isTake){
          return false;
        }else{
          return true;
        }
      }
    }
    // }else{
    //   return false;
    // }
  }

  ///listView滑动监听
  ScrollController horizontalScrollController = ScrollController();
  ScrollController verticalScrollController = ScrollController();
  ScrollController verticalTypeScrollController = ScrollController();

  var colors = <Color>[Colors.blue, Colors.orange, Colors.pinkAccent];

  Widget menuContent() {
    requestDateList();
    return Stack(
      children: [
        ListView(
          children: [
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  children: datesWidgetList(),
                ),
                ListView(
                  controller: verticalScrollController,
                  children: List.generate(listItems.length, (index) {
                    var e = listItems[index];
                    return Column(
                      children: [
                        Row(
                          children: [
                            ///用餐时段
                            CommonText(e.timeStr ?? "").addToContainer(
                                width: 50,
                                height: 80 * ((e.foodLength)??0).toDouble(),
                                alignment: Alignment.center,
                                decoration: BoxDecoration(
                                  border: Border.all(width: 0.3),
                                )),

                            Row(
                              mainAxisAlignment: MainAxisAlignment.start,
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: (e.goodsInfo ?? []).map((date) {
                                return (date.goodsList??[]).isEmpty
                                    ? Container(
                                        width: 180,
                                      )
                                    : Column(
                                        mainAxisAlignment:
                                            MainAxisAlignment.start,
                                        children:
                                            (date.goodsList ?? []).map((food) {
                                          return Row(
                                            children: [
                                              CommonText(food.goodsName ?? "")
                                                  .setWeight(1),
                                              food.canSelect&&1!=food.isTake
                                                  ? Checkbox(
                                                      value: food.selected,
                                                      onChanged: (value) {
                                                        selectFood(
                                                            food, date, e);
                                                      })
                                                  : Container()
                                            ],
                                          ).onTap(() {
                                            selectFood(food, date, e);
                                          }).addToContainer(
                                              width: 180,
                                              height: 80,
                                              decoration: BoxDecoration(
                                                  border:
                                                      Border.all(width: 0.3)),
                                              alignment: Alignment.centerLeft,
                                              padding: EdgeInsets.symmetric(
                                                  horizontal: 5));
                                        }).toList(),
                                      );
                              }).toList(),
                            )
                          ],
                        ),
                        Container(
                          height: 0.4,
                          color: Colors.black,
                        ),
                      ],
                    ).addToContainer(color: colors[index].withAlpha(20));
                  }),
                ).addToContainer(width: menuWidth).setWeight(1)
              ],
            )
          ],
          scrollDirection: Axis.horizontal,
          controller: horizontalScrollController,
          padding: EdgeInsets.all(0),
        )
      ],
    ).addToContainer(width: menuWidth);
  }

  ///头部日期显示
  List<Widget> datesWidgetList() {
    var widgetList = dateList.map((e) {
      return CommonText(e).addToContainer(
          width: 180,
          height: 50,
          alignment: Alignment.center,
          decoration: BoxDecoration(
              color: Colors.white, border: Border.all(width: 0.3)));
    }).toList();
    widgetList.insertAll(0, [
      CommonText('日期').addToContainer(
          height: 50,
          width: 50,
          alignment: Alignment.center,
          decoration: BoxDecoration(
              color: Colors.white, border: Border.all(width: 0.3))),
      Container(
          width: 0,
          height: 50,
          decoration: BoxDecoration(
              color: Colors.white, border: Border.all(width: 0.3)))
    ]);

    return widgetList;
  }

  Future<void> submitWeek() async {
    var foodDateList = <GoodsInfo>[];
    listItems.forEach((time) {
      time.goodsInfo?.forEach((date) {
        print(date.selectItems.length);
        if (date.selectItems.isNotEmpty) {
          foodDateList.add(date);
        }
      });
    });

    if (foodDateList.isEmpty) {
      showToast('请选择菜品');
      return;
    }

    showBottomInputWidget();
  }

  Future<void> submitRequest(String remark) async {
    var finish = false;
    var content = listItems.map((e) => e.toSubmitJson()).toList();
    calculatePrice();
    showLoadingDialog(msg: '提交订单...');
    try {
      var data = await PostRequest.submitWeekOrder(
          menuData?.menuId.toString(),
          menuData?.menuJson?.weekMenuModel.toString(),
          siteId,
          oldData?.selectOldId.toString(),
          time,
          orderModelType,
          remark,
          content,
          null,
          null,
          useType);
      hideDialog();
      if ('0' == data['code'].toString()) {
        var orderId = data['data']['id'].toString();
        // var totalMoney = data['data']['totalMoney'].toString();
        await payOrder(orderId, (totalPrice-oriPrice).toString());
        // showToast('提交成功');
        // finish();
      } else {
        showToast(data['msg']);
      }
    } catch (e) {
      hideDialog();
      showToast(NetErrorUtils.getNetError(e));
    }
  }

  Future<void> payOrder(String orderId, String totalMoney) async {
    showLoadingDialog(msg: '正在完成支付...');
    try {
      var data = await PostRequest.weekPayOrder(
          orderId: orderId, type: "2", totalMoney: totalMoney);
      hideDialog();
      if ('0' == data['code'].toString()) {
        showToast('支付成功');
        sendMessage(SendMessageEvent(MessageConfig.PAY_FOOD_SUCCESS));
        _printTicket();
        finish();
      } else {
        showToast(data['msg']);
      }
    } catch (e) {
      hideDialog();
      showToast(NetErrorUtils.getNetError(e));
    }
  }

  void showBottomInputWidget() {
    showBottomInput(context, title: '备注', hint: '请输入备注信息', onSubmit: (str) {
      // finish();
      submitRequest(str);
    });
  }

  @override
  void onCreated() {
    super.onCreated();
    requestRefresh();
    _initBluetoothPrinter();
    verticalScrollController.addListener(() {
      var top = verticalScrollController.offset;
      if (verticalTypeScrollController.positions.isNotEmpty) {
        verticalTypeScrollController.jumpTo(
          top,
        );
      }
    });
  }

  // PrinterBluetooth? printDevices;

  void _initBluetoothPrinter() {
    // printerManager.scanResults.listen((printers) async {
    //   // store found printers
    //   for (var device in printers) {
    //     if (device.name == "MPT-II") {
    //       printDevices = device;
    //       // printerManager.selectPrinter(printDevices!);
    //       // printerManager.stopScan();
    //       break;
    //     }
    //   }
    // });

    // printerManager.startScan(Duration(seconds: 4));
  }

  void selectFood(
    GoodsList food,
    GoodsInfo date,
    RegularWeekMenuContent time,
  ) {
    if (food.selected) {
      food.selected = false;
      food.number = 0;
      date.selectItems.remove(food);
    } else {
      if (hasLimitMoney) {
        num limitPrice = 0.0;
        if (time.timeSection == 1) {
          limitPrice = oldData?.limitData?.breakfastLimitMoney??0;
        }
        if (time.timeSection == 2) {
          limitPrice = oldData?.limitData?.lunchLimitMoney??0;
        }
        if (time.timeSection == 3) {
          limitPrice = oldData?.limitData?.dinnerLimitMoney??0;
        }

        print(food.price);
        // if(limitPrice!=null){
        //   if ((date.selectPrice() + food.price) > limitPrice??0) {
        //     showToast("${time.timeStr}超过限额");
        //     return;
        //   }
        // }
      }
      food.selected = true;
      food.number = 1;
      date.selectItems.add(food);

    }
    notifyListeners();
  }

  @override
  void dispose() {
    horizontalScrollController.dispose();
    verticalTypeScrollController.dispose();
    verticalScrollController.dispose();
    super.dispose();
  }

  void _printTicket() {
    var printData = listItems.toPrintData(dateList[0]);
    SunmiPrinterUtils.printWeekOrder(
        oldData?.elderHumanName??"", oldData?.elderHumanRoom ?? "", printData);

    // if (printDevices != null) {
    //   bluetoothPrint(printDevices!,printData);
    // }
  }

  // void bluetoothPrint(
  //     PrinterBluetooth printer, List<WeekPrintData> data) async {
    // printerManager.selectPrinter(printer);
    // const PaperSize paper = PaperSize.mm58;
    // final profile = await CapabilityProfile.load();
    // final Generator ticket = Generator(paper, profile);
    //
    // var tickets = EscPrintData.printWeekOrder(
    //     ticket, oldData?.elderHumanName??"", oldData?.elderHumanRoom ?? "", data);
    // // DEMO RECEIPT
    // final PosPrintResult res =
    //     await printerManager.printTicket(tickets);
  // }

  var totalPrice = 0.0;
  var oriPrice = 0.0;
  void calculatePrice(){
    var total = 0.0;
    var ori = 0.0;
    menuData?.menuJson?.content?.forEach((type) {
        type.goodsInfo?.forEach((date) {
          date.goodsList?.forEach((food) {
            if(food.canSelect&&1!=food.isTake){
              total+=(food.price??0)*(food.number??0);
            }
            if(1==food.oldStatus){
              ori+=((food.price??0)*(food.oldNumber??0));
            }
          });
        });
    });
    totalPrice = total;
    oriPrice = ori;
  }

}
